package com.realtyManage.springboot.Controller;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyThread implements Runnable {
    //定义100张票
    int ticket = 100;
    Object obj = new Object();
    //创建一个锁
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try{
                //加上锁,获取锁
                lock.lock();
                if (ticket>0) {
                    //考虑到实际的生活中，我们需要给每一个线程加入一定的延迟，模拟一下这种效果
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"正在出售第："+ticket--+"张票");
                }
            }finally{
                //这里面的代码一定会被执行
                //释放锁
                lock.unlock();
            }
        }
}

    public static void main(String[] args) {
        //创建MyThread对象
        MyThread mt = new MyThread();
        //创建三个窗口
        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        Thread t3 = new Thread(mt);
        //给每一个窗口设置姓名
        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");
        //开启窗口进行售票
        t1.start();
        t2.start();
        t3.start();
    }
}
